package com.gec.anan.driver.service.impl;

import com.alibaba.nacos.common.codec.Base64;
import com.gec.anan.common.execption.AnanException;
import com.gec.anan.common.result.ResultCodeEnum;
import com.gec.anan.driver.config.TencentCloudProperties;
import com.gec.anan.driver.service.CosService;
import com.gec.anan.driver.service.OcrService;
import com.gec.anan.model.vo.driver.CosUploadVo;
import com.gec.anan.model.vo.driver.DriverLicenseOcrVo;
import com.gec.anan.model.vo.driver.IdCardOcrVo;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.DriverLicenseOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.DriverLicenseOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class OcrServiceImpl implements OcrService {


    @Autowired
    private TencentCloudProperties tencentCloudProperties;
    @Autowired
    private CosService cosService;
    /**
     * 身份照片文字识别
     * @param file
     * @return
     */
    @Override
    @SneakyThrows
    public IdCardOcrVo idCardOcr(MultipartFile file) {
        //照片编程base64编码
        byte[] encode = Base64.encodeBase64(file.getBytes());
        log.info("base64编码：{}", new String(encode));
        String idCardBase64 = new String(encode);
        IDCardOCRResponse response = null;

        try {
            //实现文字识别图片
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(tencentCloudProperties.getSecretId(),
                    tencentCloudProperties.getSecretKey());
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, tencentCloudProperties.getRegion(), clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            IDCardOCRRequest req = new IDCardOCRRequest();
            req.setImageBase64(idCardBase64);
            // 返回的resp是一个IDCardOCRResponse的实例，与请求对象对应
            response = client.IDCardOCR(req);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            throw new AnanException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        }
        IdCardOcrVo idCardOcrVo = new IdCardOcrVo();
        if(StringUtils.hasText(response.getName())){
            //正面
            idCardOcrVo.setName(response.getName());
            idCardOcrVo.setGender("男".equals(response.getSex())? "1":"2");
            idCardOcrVo.setBirthday(DateTimeFormat.forPattern("yyyy/MM/dd").parseDateTime(response.getBirth()).toDate());
            idCardOcrVo.setIdcardNo(response.getIdNum());
            idCardOcrVo.setIdcardAddress(response.getAddress());
            //上传图片到cos
            CosUploadVo idcard = cosService.upload(file, "idcard");
            idCardOcrVo.setIdcardFrontUrl(idcard.getUrl());
            idCardOcrVo.setIdcardFrontShowUrl(idcard.getShowUrl());
        }else {
            //反面
            //获取身份证有效期
            String endTime= response.getValidDate().split("-")[1];
            idCardOcrVo.setIdcardExpire(DateTimeFormat.forPattern("yyyy.MM.dd").parseDateTime(endTime).toDate());
            CosUploadVo idcard = cosService.upload(file, "idcard");
            idCardOcrVo.setIdcardBackUrl(idcard.getUrl());
            idCardOcrVo.setIdcardBackShowUrl(idcard.getShowUrl());
        }
        return idCardOcrVo;
    }

    /**
     * 驾驶证识别
     * @param file
     * @return
     */
    @Override
    @SneakyThrows
    public DriverLicenseOcrVo driverLicenseOcr(MultipartFile file) {
        //照片转码
        byte[] driverLicenseBase64 = Base64.encodeBase64(file.getBytes());
        String driverLicense = new String(driverLicenseBase64);
        DriverLicenseOCRResponse response = null;
        try {
            //实现文字识别图片
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(tencentCloudProperties.getSecretId(),
                    tencentCloudProperties.getSecretKey());
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, tencentCloudProperties.getRegion(), clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DriverLicenseOCRRequest req = new DriverLicenseOCRRequest();
            req.setImageBase64(driverLicense);
            // 返回的resp是一个IDCardOCRResponse的实例，与请求对象对应
            response = client.DriverLicenseOCR(req);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            throw new AnanException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        }
        DriverLicenseOcrVo driverLicenseOcrVo = new DriverLicenseOcrVo();
        //驾驶证正反面
        if(StringUtils.hasText(response.getName())){
            //正面
            driverLicenseOcrVo.setName(response.getName());
            //类型 C1
            driverLicenseOcrVo.setDriverLicenseClazz(response.getClass_());
            //证件号
            driverLicenseOcrVo.setDriverLicenseNo(response.getCardCode());
            //有效期
            driverLicenseOcrVo.setDriverLicenseExpire(DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(response.getEndDate()).toDate());
            //初领证时间
            driverLicenseOcrVo.setDriverLicenseIssueDate(DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(response.getDateOfFirstIssue()).toDate());
            //上传图片获取回显url
            CosUploadVo driverLicenseFront = cosService.upload(file, "driverLicense");
            driverLicenseOcrVo.setDriverLicenseFrontUrl(driverLicenseFront.getUrl());
            driverLicenseOcrVo.setDriverLicenseFrontShowUrl(driverLicenseFront.getShowUrl());
        }else {
            //反面
            CosUploadVo driverLicenseBack = cosService.upload(file, "driverLicense");
            driverLicenseOcrVo.setDriverLicenseBackUrl(driverLicenseBack.getUrl());
            driverLicenseOcrVo.setDriverLicenseBackShowUrl(driverLicenseBack.getShowUrl());
        }
        return driverLicenseOcrVo;
    }
}
